<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class FlashSale extends Model
{
    protected $fillable = ['goods_id', 'goods_name', 'discount', 'started_at', 'ended_at', 'title', 'goods_number', 'buy_limit', 'sales_count', 'description'];
    protected $appends = ['status_desc'];
    protected $casts = [
        'status' => 'boolean'
    ];
    public function goods()
    {
        return $this->belongsTo('App\Goods');
    }

    public function specGoodsPrice()
    {
        return $this->belongsTo('App\SpecGoodsPrice');
    }
    // 有效的秒杀活动
    public function scopeOfActive($query)
    {
        return $query->where('status', 1)
            ->where('ended_at', '>', Carbon::now());
    }

    // 正在进行的
    public function scopeOfUnderway($query)
    {
        return $query->where('status', 1)
            ->where('started_at', '<', Carbon::now())
            ->where('ended_at', '>', Carbon::now());
    }

    public function getStatusDescAttribute()
    {
        if ($this->attributes['status'] == 0) {
            return '已停止';
        }
        if ($this->attributes['ended_at'] < Carbon::now()) {
            return '已结束';
        }
        if ($this->attributes['started_at'] > Carbon::now()) {
            return '未开始';
        }
        return '进行中';
    }
}
